package com.fancon.android.gardenjokesx.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.fancon.android.gardenjokesx.GardenJokesBaseActivity;
import com.fancon.android.gardenjokesx.R;
import com.fancon.android.gardenjokesx.adapter.FriendsAdapter;
import com.fancon.android.gardenjokesx.entity.ReportErrors;
import com.fancon.android.gardenjokesx.entity.User;
import com.fancon.android.gardenjokesx.rpc.GardenJokesApiConnect;
import com.fancon.android.gardenjokesx.rpc.JsonPaser;
import com.fancon.android.gardenjokesx.utils.UserUtil;
import com.fancon.android.multithread.RequestUI;
import com.fancon.android.ui.widget.FanconProgressBar;

public class S043Activity extends GardenJokesBaseActivity {
	private ArrayList<User> mListUser;
	private FriendsAdapter friendAdapter;
	private ListView listFriends;
	private Button mBtnFollowAll;
//	private String id;
	private String mListPhoneNumber = "";
	private String mListEmail = "";
//	private ReportErrors report;
	private String mUserID;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.common_list_friends);
		User user = UserUtil.getInfoUserLogin(getApplicationContext());
		if (user != null) {
			mUserID = user.getUser_id();
		}
		TextView tvTitleListFriends = (TextView) findViewById(R.id.common_tv_title_list_friends);
		tvTitleListFriends
				.setText(getString(R.string.s04_3_tv_title_list_friends));
		mListUser = new ArrayList<User>();
		listFriends = (ListView) findViewById(R.id.common_item_list_friends);
		mBtnFollowAll = (Button) findViewById(R.id.s04_btnFollowAll);
		ListFriendRequest request = new ListFriendRequest("S043",
				S043Activity.this);
		getGlobalState().getRequestQueue().addRequest(request);
		// event click follow all user on list
		mBtnFollowAll.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				FollowAllRequest request = new FollowAllRequest("S043",
						S043Activity.this);
				getGlobalState().getRequestQueue().addRequest(request);
			}
		});
	}

	private class ListFriendRequest extends RequestUI {

		private Activity context;
		private FanconProgressBar mProgressDialog;

		public ListFriendRequest(Object key, Activity activity) {
			super(key, activity);
			context = activity;
			mProgressDialog = FanconProgressBar.show(S043Activity.this,
					getString(R.string.common_loading));
		}

		@Override
		public void execute() throws Exception {
			// TODO Auto-generated method stub
			getContactDetails();
			// @binhbt-comment
			getListFriend(context, removeCharacter(mListPhoneNumber),
					removeCharacter(mListEmail), mUserID);

		}

		@Override
		public void executeUI(Exception ex) {
			// TODO Auto-generated method stub
			friendAdapter = new FriendsAdapter(S043Activity.this, mListUser,
					mUserID);
			Log.d("list request", "set adapter");
			listFriends.setAdapter(friendAdapter);
			mProgressDialog.dismiss();
		}
	}

	private class FollowAllRequest extends RequestUI {

		private Activity context;
		private FanconProgressBar mProgressDialog;

		public FollowAllRequest(Object key, Activity activity) {
			super(key, activity);
			context = activity;
			mProgressDialog = FanconProgressBar.show(context,
					getString(R.string.common_loading));
		}

		@Override
		public void execute() throws Exception {
			// TODO Auto-generated method stub

			// @binhbt-comment
			Log.d("follow request", "API");
			String ids = "";
			for (int i = 0; i < mListUser.size(); i++) {
				ids += mListUser.get(i).getUser_id() + ",";
				// @binhbt-comment
				// report = followUser(mUserID, mListUser.get(i).getUser_id(),
				// true);
				// if (mListUser.get(i).isIs_following() == false) {
				// if (report.getResult() == 1) {
				// Log.d("vao for", "set is following");
				// mListUser.get(i).setIs_following(true);
				// }
				// }
			}
			followUser(mUserID, ids, true);
		}

		@Override
		public void executeUI(Exception ex) {
			// @binhbt-comment
			// friendAdapter = new FriendsAdapter(S043Activity.this, mListUser,
			// mUserID);
			// Log.d("Follow reques", "set adapter");
			// listFriends.setAdapter(friendAdapter);
			mProgressDialog.dismiss();
			// Refresh
			ListFriendRequest request = new ListFriendRequest("S043",
					S043Activity.this);
			getGlobalState().getRequestQueue().addRequest(request);
		}

	}

	/**
	 * Follow or unfollow
	 * followAllUser
	 * @param userId
	 *            your id
	 * @param followUserId
	 *            user_id you want to follow or unfollow, if list with comma.
	 * @param isFollowing
	 *            true -> follow, false -> unfollow
	 * @return ReportErrors ReportErrors.result: 0: unfollow success 1: follow
	 *         success 2: follow success but depend on private mode, wait
	 *         confirm ReportErrors.message: ERR0004: limit user following
	 */
	public ReportErrors followUser(String userId, String followUserId,
			boolean isFollowing) {
		ReportErrors report = null;
		try {
//			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//			nameValuePairs.add(new BasicNameValuePair("user_id", userId));
//			nameValuePairs.add(new BasicNameValuePair("following_user_id",
//					followUserId));
//			nameValuePairs.add(new BasicNameValuePair("is_following", String
//					.valueOf(isFollowing)));
//			GardenJokesApiConnect api = new GardenJokesApiConnect(this);
//			String result = api.execPost(this, GardenJokesApiConnect.GROUP_S,
//					"registerFollowingUser", nameValuePairs);
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			nameValuePairs.add(new BasicNameValuePair("user_id", userId));
			nameValuePairs.add(new BasicNameValuePair("list_ids",
					followUserId));
			nameValuePairs.add(new BasicNameValuePair("is_following", String
					.valueOf(isFollowing)));
			GardenJokesApiConnect api = new GardenJokesApiConnect(this);
			String result = api.execPost(this, GardenJokesApiConnect.GROUP_S,
					"followAllUser", nameValuePairs);
			JsonPaser jP = new JsonPaser();
			report = jP.getReport(result);
		} catch (Exception e) {

		}
		return report;
	}

	/**
	 * Follow or unfollow
	 * 
	 * @param userId
	 *            your id
	 * @param followUserId
	 *            user_id you want to follow or unfollow, if list with comma.
	 * @param isFollowing
	 *            true -> follow, false -> unfollow
	 * @return ReportErrors ReportErrors.result: 0: unfollow success 1: follow
	 *         success 2: follow success but depend on private mode, wait
	 *         confirm ReportErrors.message: ERR0004: limit user following
	 */
	public ReportErrors followAllUser(String userId, String followUserIds,
			boolean isFollowing) {
		ReportErrors report = null;
		try {
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			nameValuePairs.add(new BasicNameValuePair("user_id", userId));
			nameValuePairs.add(new BasicNameValuePair("following_user_id",
					followUserIds));
			nameValuePairs.add(new BasicNameValuePair("is_following", String
					.valueOf(isFollowing)));
			GardenJokesApiConnect api = new GardenJokesApiConnect(this);
			String result = api.execPost(this, GardenJokesApiConnect.GROUP_S,
					"registerFollowingUser", nameValuePairs);
			JsonPaser jP = new JsonPaser();
			report = jP.getReport(result);
		} catch (Exception e) {

		}
		return report;
	}

	/*
	 * get phone number and email address from contact
	 */
	private void getContactDetails() {
		ContentResolver cr = getContentResolver();
		Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
				null, null, null);
		if (cur.getCount() > 0) {
			while (cur.moveToNext()) {
				String id = cur.getString(cur
						.getColumnIndex(ContactsContract.Contacts._ID));
				if (Integer
						.parseInt(cur.getString(cur
								.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
					Cursor pCur = cr.query(
							ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
							null,
							ContactsContract.CommonDataKinds.Phone.CONTACT_ID
									+ " = ?", new String[] { id }, null);
					while (pCur.moveToNext()) {

						String phoneNumber = pCur
								.getString(pCur
										.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
						mListPhoneNumber += phoneNumber + ",";

					}
					pCur.close();
				}
				Cursor emailCur = cr.query(
						ContactsContract.CommonDataKinds.Email.CONTENT_URI,
						null, ContactsContract.CommonDataKinds.Email.CONTACT_ID
								+ " = ?", new String[] { id }, null);
				while (emailCur.moveToNext()) {
					String email = emailCur
							.getString(emailCur
									.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
					mListEmail += email + ",";
				}
				emailCur.close();

			}
		}
	}

	/**
	 * Call API getListUserByContactAddress to get list user is my friend on
	 * meshtiles from contact address.
	 * 
	 * @param listPhoneNumber
	 * @param listEmail
	 * @param userId
	 */
	private void getListFriend(Activity context, String listPhoneNumber,
			String listEmail, String userId) {

		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
		nameValuePairs.add(new BasicNameValuePair("list_mobile_phone",
				listPhoneNumber));
		nameValuePairs.add(new BasicNameValuePair("list_email", listEmail));
		nameValuePairs.add(new BasicNameValuePair("user_id", userId));
		GardenJokesApiConnect api = new GardenJokesApiConnect(context);
		String result = api.execPost(getApplicationContext(),
				GardenJokesApiConnect.GROUP_S, "getListUserByContactAddress",
				nameValuePairs);
		Log.d("json list friend", result);
		JsonPaser json = new JsonPaser();
		mListUser = json.getListUser(result);
	}

	/**
	 * Remove "," at the end string.
	 * 
	 * @param str
	 * @return
	 */
	private String removeCharacter(String str) {

		return str.substring(0, str.length() - 1);
	}
}
